package com.kakame.ahasekai.biz.user;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import com.kakame.ahasekai.common.util.DbUtil;

@Component
public class UserDaoImpl implements UserDao {

    @Resource
    private MongoTemplate mongoTemplate;

    public void batchInsert(List<UserVo> userList) {
        //分组批量多次插入 每次2000条
        List<List<UserVo>> groupList = DbUtil.spliceList(userList, 0);
        for (List<UserVo> list : groupList) {
            mongoTemplate.insert(list, UserVo.class);
        }
    }

    public void insert(UserVo user) {
        mongoTemplate.save(user);
    }

    public UserVo findById(String userId) {
        Query query = new Query(Criteria.where("user_id").is(userId));
        UserVo ent = mongoTemplate.findOne(query, UserVo.class);
        return ent;
    }

    public void update(UserVo user) {
        Query query = new Query(Criteria.where("_id").is(user.getUserId()));
        Update update = new Update()
                .set("nickname", user.getNickname());
        //更新查询返回结果集的第一条
        mongoTemplate.updateFirst(query, update, UserVo.class);
    }

    public void delete(String userId) {
        Query query = new Query(Criteria.where("_id").is(userId));
        mongoTemplate.remove(query, UserVo.class);
    }
}